package com.macro.mall.portal.controller;

import com.alibaba.fastjson.JSON;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.exception.ApiException;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.mapper.OmsOrderMapper;
import com.macro.mall.mapper.OmsOrderSettingMapper;
import com.macro.mall.model.OmsOrder;
import com.macro.mall.model.OmsOrderExample;
import com.macro.mall.model.OmsOrderSetting;
import com.macro.mall.portal.domain.OrderParam;
import com.macro.mall.portal.domain.PmsPortalProductDetail;
import com.macro.mall.portal.dto.PmsProductDto;
import com.macro.mall.portal.service.PmsPortalProductService;
import com.macro.mall.portal.service.activityImpl.ActivityImpl;
import com.quyum.mall.market.config.RedisKey;
import com.quyum.mall.market.dto.MarketSmsGroupBuyDTO;
import com.quyum.mall.market.entity.MarketSmsGroupBuy;
import com.quyum.mall.market.entity.MarketSmsGroupBuyOrder;
import com.quyum.mall.market.entity.MarketSmsRound;
import com.quyum.mall.market.example.MarketSmsGroupBuyOrderExample;
import com.quyum.mall.market.mapper.MarketSmsGroupBuyMapper;
import com.quyum.mall.market.mapper.MarketSmsGroupBuyOrderMapper;
import com.quyum.mall.market.mapper.MarketSmsRoundMapper;
import com.quyum.mall.market.service.activity.GroupBuyService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhouboyu
 */
@Controller
@RequestMapping("/groupBuy")
public class GroupBuyController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private ActivityImpl activity;
    @Autowired
    private GroupBuyService groupBuyService;
    @Autowired
    private PmsPortalProductService portalProductService;
    @Autowired
    private OmsOrderSettingMapper orderSettingMapper;
    @Autowired
    private OmsOrderMapper omsOrderMapper;
    @Autowired
    private MarketSmsGroupBuyMapper smsGroupBuyMapper;
    @Autowired
    private MarketSmsGroupBuyOrderMapper smsGroupBuyOrderMapper;
    @Autowired
    private MarketSmsRoundMapper roundMapper;

    @ApiOperation("团购专场详情展示")
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<PmsProductDto>> recommendList(@RequestParam(required = false,value = "pageSize", defaultValue = "5") Integer pageSize,
                                                                 @RequestParam(required = false,value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                 @RequestParam Long roundId) {
        return this.activity.getDetails(pageSize, pageNum, roundId);
    }

    @ApiOperation("获取团购专场列表页")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<MarketSmsRound>> list() {
        return this.activity.getListCommonResult(MarketSmsRound.TYPE.GROUP_BUYING.VALUE);
    }

    @ApiOperation("获取团购专场详情")
    @RequestMapping(value = "/detail/one", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<MarketSmsRound> detailOne(Long roundId) {
        String key = RedisKey.ROUND_STARTING_KEY+roundId;
        Object o = this.redisService.get(key);
        if (o!=null){
            MarketSmsRound round = (MarketSmsRound) o;
            round.setProducts(null);
            return CommonResult.success(round);
        }else{
            return CommonResult.failed("该场次活动已经结算");
        }
    }
    @ApiOperation("获取团购专场详情")
    @RequestMapping(value = "/getGroupBuyByProductId", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<MarketSmsGroupBuyDTO>> getGroupBuyByProductId(@RequestParam Long roundId,
                                                                                 @RequestParam Long productId,
                                                                                 @RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                                                                 @RequestParam(required = false,defaultValue = "5") Integer pageSize)
    {
        CommonPage<MarketSmsGroupBuyDTO> groupBuyByProductId = this.activity.getGroupBuyByProductId(roundId, productId, pageNum, pageSize);
        return CommonResult.success(groupBuyByProductId);
    }
    /**
     * 通过订单id获取团购GroupBuyId用来分享
     * @author zhouboyu
     * @Date 2020年10月22日
     * @param orderId
     * @return
     */
    @ApiOperation("通过订单id获取团购GroupBuyId用来分享")
    @RequestMapping(value = "/getGroupIdByOrderId", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult getGroupIdByOrderId(@RequestParam Long orderId) {
        Long groupBuyId = this.groupBuyService.getGroupIdByOrderId(orderId);
        if(groupBuyId.equals(-1L)){
            return CommonResult.failed("团购不存在");
        }else{
            return CommonResult.success(groupBuyId);
        }
    }


    @ApiOperation("查看团购商品详情")
    @RequestMapping(value = "/getProductByGroupBuyId", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult getProductId(Long groupBuyId){
        MarketSmsGroupBuyDTO groupBuyDTO = this.groupBuyService.getGroupBuyByGroupBuyId(groupBuyId);
        PmsPortalProductDetail detail = this.portalProductService.detail(groupBuyDTO.getProductId(), groupBuyDTO);
        detail.setMarketSmsGroupBuyDTO(groupBuyDTO);
        return CommonResult.success(detail);
    }
    /**
     * 拼团
     * @author zhouboyu
     * @Date 2020年10月22日
     * @param orderParam
     * @return
     */
    @ApiOperation("拼团")
    @RequestMapping(value = "/participateInGroupBuy", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public CommonResult participateInGroupBuy(@RequestBody OrderParam orderParam) {
        Map<String, Object> params = JSON.parseObject(JSON.toJSONString(orderParam),Map.class);
        Long id = null;
        try {
            id= this.activity.participateInGroupBuy(params);
        } catch (ApiException e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
        return CommonResult.success(id);
    }
    /**
     * 开团
     * @author zhouboyu
     * @Date 2020年10月22日
     * @param orderParam
     * @return
     */
    @ApiOperation("开团")
    @RequestMapping(value = "/openGroupBuy", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public CommonResult openGroupBuy(@RequestBody OrderParam orderParam) {
        Map<String, Object> params = JSON.parseObject(JSON.toJSONString(orderParam),Map.class);
        Long id = null;
        try {
            id= this.activity.openGroupBuy(params);
        } catch (ApiException e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
        return CommonResult.success(id);
    }

    /**
     * 获取团购剩余时间
     * @author zhouboyu
     * @Date 2020年10月22日
     * @return
     */
    @ApiOperation("获取团购剩余时间")
    @RequestMapping(value = "/getEndTime", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult getEndTime(@RequestParam Long orderId) {
        Map<String, Object> result = new HashMap<>();
        Integer residueNum =0;
        Long residueTime = 0L;
        Long groupIdByOrderId = this.groupBuyService.getGroupIdByOrderId(orderId);
        MarketSmsGroupBuy groupBuy = this.smsGroupBuyMapper.selectByPrimaryKey(groupIdByOrderId);
        MarketSmsGroupBuyOrderExample example = new MarketSmsGroupBuyOrderExample();
        example.createCriteria().andGroupBuyIdEqualTo(groupBuy.getId());
        List<MarketSmsGroupBuyOrder> marketSmsGroupBuyOrders = this.smsGroupBuyOrderMapper.selectByExample(example);
        OmsOrderSetting omsOrderSetting = this.orderSettingMapper.selectByPrimaryKey(1L);
        List<Long> orderIds = new ArrayList<>();
        if(!CollectionUtils.isEmpty(marketSmsGroupBuyOrders)){
            orderIds = marketSmsGroupBuyOrders.stream().map(MarketSmsGroupBuyOrder::getOrderId).collect(Collectors.toList());
            OmsOrderExample omsOrderExample = new OmsOrderExample();
            omsOrderExample.createCriteria().andStatusIn(Arrays.asList(new Integer[]{8,0})).andIdIn(orderIds);
            Long l = this.omsOrderMapper.countByExample(omsOrderExample);
            residueNum = groupBuy.getGroupSize()-l.intValue();
            OmsOrder omsOrder = this.omsOrderMapper.selectByPrimaryKey(groupBuy.getFirstOrderId());
            SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
            System.out.println("付款时间-----------------"+omsOrder.getPaymentTime().getTime());
            System.out.println("付款时间sdf-----------------"+sdf.format(omsOrder.getPaymentTime().getTime()));
            System.out.println("当前时间-----------------"+System.currentTimeMillis());
            residueTime = omsOrder.getPaymentTime().getTime()+omsOrderSetting.getGroupBuyOrderOvertime()*60*1000-System.currentTimeMillis();
        }
        result.put("residueNum",residueNum);
        result.put("residueTime",residueTime);
        return CommonResult.success(result);
    }
}
